﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Marbles.Core.Controls
{
    [ToolboxData("<{0}:TabContainer runat=server></{0}:TabContainer>")]
    public class TabContainer : WebControl
    {
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        [Browsable(false)]
        public virtual TabCollection Tabs
        {
            get
            {
                if (_tabs == null) { _tabs = new TabCollection(this); }
                return _tabs;
            }
        }

        private TabCollection _tabs;
        private Panel parent;

        protected override void CreateChildControls()
        {
            parent = new Panel();
            parent.ID = this.ClientID;
            LiteralControl lt = new LiteralControl();

            this.Controls.Add(parent);
            parent.Controls.Add(lt);

            lt.ID = this.ClientID + "_tabs";
            lt.Text = "<ul>";

            foreach (Tab t in Tabs)
            {
                lt.Text += "<li><a href=\"#" + t.ClientID + "\">" + t.Title + "</a></li>";
            }
            lt.Text += "</ul>";

            foreach (Tab t in Tabs)
            {
                parent.Controls.Add(t);
            }

            LiteralControl script = new LiteralControl();
            script.ID = this.ClientID + "_script";
            script.Text = "<script language=\"javascript\" type=\"text/javascript\">";

            script.Text += string.Format("$(\"#{0}\").tabs(", parent.ClientID);

            script.Text += ");";
            script.Text += "</script>";
            this.Controls.Add(script);
        }

    }


    [ToolboxData("<{0}:Tab runat=server></{0}:Tab>")]
    public class Tab : Panel
    {

        public string Title { get { object obj = ViewState["Title"]; return (obj == null ? "" : obj.ToString()); } set { ViewState["Title"] = value; } }
    }

    public class TabCollection : ControlCollection
    {
        public TabCollection(Control owner)
            : base(owner)
        {
        }

        public new Tab this[int index] { get { return base[index] as Tab; } }

        public override void Add(Control child)
        {
            base.Add((Tab)child);
        }

        public override void AddAt(int index, Control child)
        {
            base.AddAt(index, (Tab)child);
        }
    }
}
